package maple.thelittleredbook.interaction.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import maple.thelittleredbook.interaction.entity.Like;
import org.apache.ibatis.annotations.*;

/**
 * 点赞Mapper接口
 * 负责点赞关系管理
 */
@Mapper
public interface LikeMapper extends BaseMapper<Like> {

    /**
     * 根据用户ID和目标获取点赞记录
     *
     * @param userId 用户ID
     * @param targetId 目标ID（内容ID或评论ID）
     * @param targetType 目标类型（CONTENT或COMMENT）
     * @return 点赞记录，如果未点赞则返回null
     */
    @Select("SELECT * FROM likes " +
            "WHERE user_id = #{userId} AND target_id = #{targetId} AND target_type = #{targetType}")
    Like selectLikeByUserAndTarget(@Param("userId") Long userId,
                                   @Param("targetId") Long targetId,
                                   @Param("targetType") String targetType);

    /**
     * 删除点赞记录
     *
     * @param userId 用户ID
     * @param targetId 目标ID
     * @param targetType 目标类型
     * @return 删除的记录数
     */
    @Delete("DELETE FROM likes " +
            "WHERE user_id = #{userId} AND target_id = #{targetId} AND target_type = #{targetType}")
    int deleteLike(@Param("userId") Long userId,
                   @Param("targetId") Long targetId,
                   @Param("targetType") String targetType);

    /**
     * 插入点赞记录
     *
     * @param userId 用户ID
     * @param targetId 目标ID
     * @param targetType 目标类型
     * @return 插入的记录数
     */
    @Insert("INSERT INTO likes (user_id, target_id, target_type, created_at) " +
            "VALUES (#{userId}, #{targetId}, #{targetType}, NOW())")
    int insertLike(@Param("userId") Long userId,
                   @Param("targetId") Long targetId,
                   @Param("targetType") String targetType);

    /**
     * 统计某个目标的点赞总数（用于数据校验）
     *
     * @param targetId 目标ID
     * @param targetType 目标类型
     * @return 点赞总数
     */
    @Select("SELECT COUNT(*) FROM likes " +
            "WHERE target_id = #{targetId} AND target_type = #{targetType}")
    int countLikesByTarget(@Param("targetId") Long targetId,
                           @Param("targetType") String targetType);
}